package modelimplementation

import (
	"salarypayment-case/Model"
	"time"
)

type UnionAffiliation struct {
	itsMemberId       int
	itsDues           float64
	itsServiceCharges map[time.Time]ServiceCharge
}

func CreateUnionAffiliation(memberid int, dues float64) *UnionAffiliation {
	return &UnionAffiliation{itsMemberId: memberid, itsDues: dues}
}

func (ua *UnionAffiliation) GetServiceCharge(date time.Time) ServiceCharge {
	return ua.itsServiceCharges[date]
}

func (ua *UnionAffiliation) GetMemberId() int {
	return ua.itsMemberId
}

func (ua *UnionAffiliation) GetDues() float64 {
	return ua.itsDues
}

func (ua *UnionAffiliation) AddServiceCharge(date time.Time, amount float64) {
	var sc ServiceCharge = ServiceCharge{itsDate: date, itsAmount: amount}
	ua.itsServiceCharges[date] = sc
}

func (ua *UnionAffiliation) CalculateDeductions(pc Model.Paycheck) float64 {
	totalServiceCharge := 0.0
	totalDues := 0.0

	for date, as := range ua.itsServiceCharges {
		dt1 := pc.GetPayPeriodStartDate()
		dt2 := pc.GetPayPeriodEndDate()

		if date.After(dt1) && date.Before(dt2) {
			totalServiceCharge += as.GetAmount()
		}
	}

	fridays := ua.NumberOfFridaysInPayPeriod(pc.GetPayPeriodStartDate(),pc.GetPayPeriodEndDate())

	totalDues = ua.itsDues * float64(fridays)

	return totalDues + totalServiceCharge
}

func (ua *UnionAffiliation) NumberOfFridaysInPayPeriod(payPeriodStart time.Time, payPeriodEnd time.Time) int {
	fridays := 0

	for date := payPeriodStart; date.Before(payPeriodEnd); date = date.AddDate(0, 0, 1) {
		if date.Weekday() == time.Friday {
			fridays++
		}
	}

	return fridays
}
